//
//  Rotator.cpp
//  all_test04
//
//  Created by Jarosław Wojtasik on 18.06.2013.
//  Copyright (c) 2013 Jarosław Wojtasik. All rights reserved.
//

#include "Rotator.h"
#include <cmath>
#define PI 3.14159

Rotator::Rotator(): _targetAngle( .0 ), _currAngle( .0 ) {
	_bitmap = al_load_bitmap( "base1Gun.bmp" );
}

Rotator::~Rotator() {
    
}



void Rotator::turnTowardPoint( double x, double y ) {
	x -= 400;
	y -= 300;
    double l = sqrt( x*x + y*y );
	double sinVal = y / l;
	_targetAngle = asin( sinVal );
	if ( _targetAngle  < 0 ) {
		_targetAngle += 2 * PI;
	}
}

void Rotator::update() {
    if ( _targetAngle == _currAngle ) return;

	double dir = 0;
	double dif;
	//if ( _targetAngle < _currAngle ) {
	//	dir = -1;
	//	dif = _currAngle - _targetAngle;
	//} else {
	//	dif = _currAngle - _targetAngle;
	//	dir = 1;
	//}
	dif = _targetAngle - _currAngle;
	dir = dif / abs( dif );

	if ( abs( dif ) > PI ) dir = -dir;

	_currAngle += 0.2 * dir;

	if ( _currAngle >= 2 * PI )  _currAngle -= (2*PI);
	if ( _currAngle <= 0 ) _currAngle  += (2*PI);
}

void Rotator::draw() {
    ALLEGRO_TRANSFORM current, toUse;

	al_copy_transform( &current, al_get_current_transform() );
	al_identity_transform( &toUse );

	al_translate_transform( &toUse, -1, -71 );
	al_rotate_transform( &toUse, _currAngle );
	al_translate_transform( &toUse, 400, 300 );
	al_compose_transform( &toUse, &current );
	al_use_transform( &toUse );
    al_draw_bitmap( _bitmap, .0, .0, 0 );
	al_use_transform( &current );
		
}